package com.mashibing.class04;

/**
 * @Auther: huangxiaode
 * @Date: 2024-01-30 - 01 - 30 - 21:24
 * @Description: com.mashibing.class04
 * @version: 1.0
 */
public class Code01_ReverseList {
    public static class Node {
        public int value;
        public Node next;

        public Node(int data) {
            value = data;
        }
    }

    public static class DoubleNode {
        public int value;
        public DoubleNode last;
        public DoubleNode next;

        public DoubleNode(int data) {
            value = data;
        }
    }

    public static Node reverseLinkedList(Node head) {
        Node pre = null;
        Node next = null;
        while (head != null) {
            next = head.next; // 记录head的下一个位置记录一下.
            head.next = pre; // pre的初始值是null,反转前的header头指针的next 指向null (修改next指针)
            pre = head; // pre 来到了head节点.
            head = next; // 当前指针后移 head往后走.
        }
        return pre;
    }

    public static void f(Node head){
        head = head.next;
    }

    public static DoubleNode reverseDoubleList(DoubleNode head) {
        DoubleNode pre = null; // 前指针
        DoubleNode next = null;// 后指针
        while (head != null) {
            // step1 备份当前节点的下一个节点 赋值给next
            next = head.next;
            // step2 修改当前节点的前后指针.
            head.next = pre;
            head.last = next;
            // step3: 备份当前节点 赋值给pre
            pre = head;
            // step: 当前节点往后移.
            head = next;
        }
        return pre;
    }

    // for test
    public static void main(String[] args) {
        Node node1 = new Node(1);
        node1.next = new Node(2);
        node1.next.next = new Node(3);

        node1 = reverseLinkedList(node1);

        while (node1 !=null){
            System.out.println(node1.value + " ");
            node1 = node1.next;
        }
        System.out.println();
    }
}
